package com.app.controller;

import com.alibaba.fastjson.JSON;
import com.app.conf.RedisService;

import com.app.model.*;
import com.app.service.*;
import com.app.util.*;
import com.app.vo.LivePortendVo;
import com.app.vo.LiveVo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.live.v20180801.models.CreateRecordTaskRequest;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


@RestController
@Controller
@Slf4j
public class LiveBroadcastController {

    @Autowired
    private RedisService redisService;

    @Autowired
    UserService userService;

    @Autowired
    LiveService liveService;

    @Autowired
    LivePortendService livePortendService;
    @Autowired
    EnterpriseService enterpriseService;
    @Autowired
    JobPublishService jobPublishService;
    @Autowired
    CustomerService customerService;
    @Autowired
    LiveVideoService liveVideoService;

    //开启直播
    @PostMapping("/liveStart")
    public Result<Object> liveStart(
                                    @RequestParam(required = false) String url,
                                    @RequestParam(required = false) Integer id,
                                    @RequestParam(required = false) String pushConf,
                                    HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");

        }
        String mobile = TokenUtils.verify(token);
        UserModel user = userService.getUserByMobile(mobile);

        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        String name = customerService.getCustomerById(user.getCId()).getRealName();
        LivePortendModel livePortendModel = new LivePortendModel();
        livePortendModel.setUserId(user.getId());
        livePortendModel.setStartTime(CommonHelp.getNowTimestamp().toString());
        LivePortendModel liveModel = livePortendService.getModelListByModel(livePortendModel);
        UUID uuid = UUID.randomUUID();
        LiveRecordModel liveRecord = new LiveRecordModel();
        liveRecord.setId(id);
        liveRecord.setRoomNo(String.valueOf("jintaRoom" + uuid));
        liveRecord.setRoomName(liveModel.getTitle());
        liveRecord.setCoverUrl(liveModel.getCoverUrl());
        liveRecord.setStartTime(CommonHelp.getNowTimestamp());
        liveRecord.setCompanyList(liveModel.getComIds());
        liveRecord.setUserId(user.getId());
        liveRecord.setUrl(url);
        liveRecord.setRealName(name);
        liveRecord.setIntroduce(liveModel.getIntroduce());
        liveRecord.setFaceUrl(user.getFaceUrl());
        String comIds[] = liveModel.getComIds().split(",");
        String publishIds[] = liveModel.getPublishIds().split(",");
        List<EnterpriseModel> enterpriseModelList = enterpriseService.findModelByIds(comIds);
        List<JobPublishModel> jobPublishModelList = jobPublishService.getComPublishById(publishIds);
        Map<String,String> publistMap = new HashMap<>();
        for (int i = 0; i < enterpriseModelList.size(); i++) {
            List<String> ids=new ArrayList<>();
            for (int j = 0; j < jobPublishModelList.size(); j++) {
                if(enterpriseModelList.get(i).getId().equals(jobPublishModelList.get(j).getEnrollId()))
                {
                    ids.add(jobPublishModelList.get(j).getId().toString());
                }
            }
            if(!ids.isEmpty())
            {
                publistMap.put(enterpriseModelList.get(i).getId().toString(),String.join(",", ids));
            }

        }
        JSONObject job = JSONObject.fromObject(publistMap);
        System.out.println(job.toString());
        liveRecord.setPositionData(job.toString());
        liveRecord.setPushConf(pushConf);
        liveRecord.setAudience(0);//观众人数
        liveRecord.setWaitingImg("https://mc.qcloudimg.com/static/img/daeed8616ac5df256c0591c22a65c4d3/pause_publish.jpg");
        // 写入缓存
        List<LiveRecordModel> liveList = (List<LiveRecordModel>) redisService.getStringKey("jintaLiveList");
        if (liveList == null) {
            liveList = new ArrayList<>();
        }
        Date date = new Date();
        //推流地址
        String txTime = TencentYunVedioUtil.to16Hex(DateUtil.addDays(date, 1));
        // 填写自己的streamName
        String streamName = liveRecord.getRoomNo();//streamName就是房间号

        StringBuffer sb = new StringBuffer();

        String pushUrlHead = TencentYunVedioUtil.pushUrl;

        // String stream_id = TencentYunVedioUtil.bizid();

        sb.append(pushUrlHead)
                .append(liveRecord.getRoomNo())
                .append("?")
                .append("txSecret=")
                .append(TencentYunVedioUtil.genSign(TencentYunVedioUtil.push_key, streamName, txTime))
                .append("&")
                .append("txTime=")
                .append(txTime);
        liveRecord.setSb(sb);
        System.out.println(txTime);
        //过期时间 16进制的unix时间戳

        String ptxTime = TencentYunVedioUtil.to16Hex(TencentYunVedioUtil.addOneDay());

        StringBuffer psb = new StringBuffer();

        psb.append(TencentYunVedioUtil.playUrl_flv)
                .append(liveRecord.getRoomNo())
                .append(".m3u8")
                .append("?")
                .append("txSecret=")
                .append(TencentYunVedioUtil.genSign(TencentYunVedioUtil.play_key, streamName, txTime))
                .append("&")
                .append("txTime=")
                .append(txTime);
        liveRecord.setPsb(psb);
        liveList.add(liveRecord);
        redisService.setStringKey("jintaLiveList", liveList);
        LiveVo vo = new LiveVo();
        vo.setRoomName(liveRecord.getRoomName());
        vo.setRoomId(liveRecord.getRoomNo());
        vo.setIntroduce(liveRecord.getIntroduce());
        vo.setCover(liveRecord.getCoverUrl());
        return Result.success(vo);
    }

    public static void main(String[] args) {
        List<String> list=new ArrayList<String>();
        list.add(String.valueOf(1));
        list.add(String.valueOf(2));
        String stringFromList = String.join(",", list);
        System.out.println(stringFromList);
    }


    //录制直播回放
    @PostMapping("/doCreateRecordTask")
    public Result<Object> createRecordTask(
            @RequestBody JSONObject json) throws TencentCloudSDKException {


        //录制直播回放
        CreateRecordTaskRequest req = new CreateRecordTaskRequest();

        //流名称
        req.setStreamName(json.get("stream_id").toString());
        //推流域名
        req.setDomainName(TencentYunVedioUtil.domainUrl);
        //推流路径
        req.setAppName(json.get("appname").toString());
        //绑定模板ID
        req.setTemplateId(1046334L);
        //录制开始时间(不传为立即开始)
//        Long dateStart = CommonHelp.getNowTimestamp().getTime()/1000L;
//        req.setStartTime(dateStart);
        //录制结束时间
        Long dateEnd = DateUtil.addDays(CommonHelp.getNowTimestamp(), 1).getTime() / 1000L;
        req.setEndTime(dateEnd);
        String msg = LiveUtils.CreateRecordTask(req);
        log.info("⭐⭐⭐⭐⭐⭐⭐⭐⭐直播录制开始返回信息：" + msg);
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(msg);
        List<LiveRecordModel> liveList = (List<LiveRecordModel>) redisService.getStringKey("jintaLiveList");
        for (int i = 0; i < liveList.size(); i++) {
            if (json.get("stream_id").toString().equals(liveList.get(i).getRoomNo())) {
                liveList.get(i).setTaskId(jsonObject.getString("TaskId"));
            }
        }
        redisService.setStringKey("jintaLiveList", liveList);
        return Result.success("回调成功");
    }


    //录制完成后回调
    @PostMapping("/doEndRecordTask")
    public Result<Object> doEndRecordTask(
            @RequestBody JSONObject json) throws TencentCloudSDKException {

        String roomNo = json.get("stream_id").toString();//获取直播流名称（等于房间号）

        String videoUrl = json.get("video_url").toString();//获取回放地址
        LiveVideoModel model = new LiveVideoModel();
        //插入已完成直播记录
        model.setVideoUrl(videoUrl);
        model.setRoomNo(roomNo);
        liveVideoService.insert(model);
        return Result.success("回调成功");
    }

    //直播记录
    @GetMapping("/liveEnd")
    public Result<Object> liveEnd(@RequestParam(required = false) String roomNo,
                                  HttpServletRequest request) throws TencentCloudSDKException {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");

        }
        String mobile = TokenUtils.verify(token);
        UserModel user = userService.getUserByMobile(mobile);

        if (user == null) {
            return Result.error(405, "用户不存在");
        }

        return Result.success(liveService.liveEnd(roomNo));
    }


    //根据ID获取redis中封面
    @GetMapping("/getLiveCoverUrlList")
    public Result<Object> getLiveCoverUrlList(@RequestParam(required = false) String roomNos,
                                              HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");

        }
        String mobile = TokenUtils.verify(token);
        UserModel user = userService.getUserByMobile(mobile);

        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        return Result.success(liveService.getLiveCoverUrlList(roomNos));
    }


    //查询全部直播列表
    @GetMapping("/getLiveAllList")
    public Result<Object> getLiveAllList(HttpServletRequest request, int type, int page, int limit) {
        return Result.success(liveService.getLiveAllList(type, page, limit));
    }

    //查询全部直播列表
    @GetMapping("/getLiveByRoom")
    public Result<Object> getLiveByRoom(HttpServletRequest request, String roomNo) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");

        }
        String mobile = TokenUtils.verify(token);
        UserModel user = userService.getUserByMobile(mobile);

        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        List<LiveRecordModel> liveList = (List<LiveRecordModel>) redisService.getStringKey("jintaLiveList");
        if (liveList == null) {
            return Result.success("无直播列表");
        }
        LiveRecordModel model = null;
        for (int i = 0; i < liveList.size(); i++) {
            if (StringTool.isNotEmpty(liveList.get(i).getRoomNo()) && liveList.get(i).getRoomNo().equals(roomNo)) {
                model = liveList.get(i);
            }
        }
        if (model == null) {
            return Result.success("直播不存在");
        }
        return Result.success(model);
    }

    //根据房间号获取redis中企业岗位信息
    @GetMapping("/getLivePostList")
    public Result<Object> getLivePostList(@RequestParam(required = false) String roomNo,
                                          HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");

        }
        String mobile = TokenUtils.verify(token);
        UserModel user = userService.getUserByMobile(mobile);

        if (user == null) {
            return Result.error(405, "用户不存在");
        }

        return Result.success(liveService.getLivePostList(roomNo));
    }

    //根据房间号获取结束直播信息
    @GetMapping("/getEndLive")
    public Result<Object> getEndLive(@RequestParam(required = false) String roomNo,
                                          HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");

        }
        String mobile = TokenUtils.verify(token);
        UserModel user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        return Result.success(liveService.getEndLive(roomNo));
    }


    /**
     * 直播预告列表
     */
    @GetMapping("/livePortendList")
    @ResponseBody
    public Result<Object> getLivePortendList(HttpServletRequest request, LivePortendModel model) {
        model.setStatus(2);
        Page<LivePortendModel> modelPage = livePortendService.modelPage(model);
        LivePortendVo vo = new LivePortendVo();
        for (int i = 0; i < modelPage.getRecords().size(); i++) {
            SimpleDateFormat simpleDateFormatFair = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Timestamp data1 = Timestamp.valueOf(String.valueOf(modelPage.getRecords().get(i).getStartTime()));//开始时间
            Timestamp data2 = Timestamp.valueOf(String.valueOf(modelPage.getRecords().get(i).getEndTime()));//结束时间
            String time = simpleDateFormatFair.format(data1);
            String time2 = simpleDateFormatFair.format(data2);
            modelPage.getRecords().get(i).setStartTime(time);
            modelPage.getRecords().get(i).setEndTime(time2);
        }
        vo.setList(modelPage.getRecords());
        vo.setCount((int)modelPage.getTotal());
        return Result.success(vo);
    }

    /**
     * 直播预告列表
     */
    @GetMapping("/livePortendDetailed")
    @ResponseBody
    public Result<Object> livePortendDetailed(HttpServletRequest request, Integer id) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String mobile = TokenUtils.verify(token);
        UserModel user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        LivePortendModel model = livePortendService.getModelById(id);
        String comIds[] = model.getComIds().split(",");
        String publishIds[] = model.getPublishIds().split(",");
        List<EnterpriseModel> enterpriseModelList = enterpriseService.findModelByIds(comIds);
        List<JobPublishModel> jobPublishModelList = jobPublishService.getComPublishById(publishIds);
        for (int i = 0; i < enterpriseModelList.size(); i++) {
            List<JobPublishModel> jobPublishModels = new ArrayList<>();
            for (int j = 0; j < jobPublishModelList.size(); j++) {

                if(enterpriseModelList.get(i).getId().equals(jobPublishModelList.get(j).getEnrollId()))
                {
                    jobPublishModels.add(jobPublishModelList.get(j));
                }
            }
            enterpriseModelList.get(i).setJobPublishList(jobPublishModels);
        }
        model.setEnterpriseList(enterpriseModelList);
        return Result.success(model);
    }

}